package com.apexedu.portal.controller;

import com.apexedu.framework.jdbc.handler.PageHandler;
import com.apexedu.framework.util.*;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.lbwsclient.LiveBosWebServiceUtils;
import com.apexedu.lbwsclient.document.Document;
import com.apexedu.lbwsclient.document.DocumentEntry;
import com.apexedu.portal.constant.ActionConstant;
import com.apexedu.portal.entity.*;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.util.DateUtil;
import com.apexedu.util.FileUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.json.JsonUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.activation.DataHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.*;



/**
 * Created by janabo on 2014-12-11.
 * 移动应用返回数据
 */
@Controller
@SessionAttributes("userid")
public class AppController extends BaseController {
    private static final Log LOG = LogFactory.getLog(AppController.class);

    private static final String portalKey = ConfigUtil.getString("portalCode");//门户接入号
	private static final String casLoginUrl = ConfigUtil.getString("cas.server.url");

    String attachLiveBosObjName = "V_OA_SendDocument_NJCI_V3";// 即Livebos对象名【适用于交院的OA】，又是文件目录名。linux注意大小写
    String attachLiveBosFieldName = "GDFJ";

	@RequestMapping("/se/news")
    public
    @ResponseBody
    String getVersion() {
        return "2.0";
    }

    @RequestMapping(value = ActionConstant.App.RequestMapping_news)
    @ResponseBody
    public String getNews(ModelMap map, HttpServletRequest request, Pager pager) {
		String title = request.getParameter("title");
		String stime = request.getParameter("stime");
		String etime = request.getParameter("etime");
		String type = request.getParameter("type")==null?"":request.getParameter("type");
        String dbsql = "select * from T_DB t where t.code = 'oa' and state = '1'";
        TDb tdb = DBUtil.queryBean(dbsql,TDb.class);
        String oaurl = tdb.getLink();
        List<Notice> notices = new ArrayList<Notice>();
        String sql = "", sqlwhere ="";
        if(type.equals("1")){//校内通知
            sql = "select to_char(id) id,to_char(TITLE) name, to_char(pubtime,'yyyy-mm-dd')  createdate," +
                    "(SELECT NAME from LBORGANIZATION where id= fbbm) fbr, visits djs,content xxnr, decode(length(attachment), null, ''," +
                    " '"+oaurl+"/UIProcessor?Table=V_TBLOG_XNTZ&ID='|| id ||'&Column=Attachment&operate=Download&Type=Attachment') attachment, " +
                    "attachment attach, decode(dbms_lob.getlength(picture1), null, ''," +
                    " '"+oaurl+"/FormOperate?Table=V_TBLOG_XNTZ&ID='|| id ||'&Column=Picture1&operate=Download&Type=View') picture1, " +
                    "decode(length(picture2), null, '', '"+oaurl+"/FormOperate?Table=V_TBLOG_XNTZ&ID='|| id ||'&Column=Picture2&operate=Download&Type=View') picture2, lyid ";
            sqlwhere = "from TBLOG where (category = 504 or category=505) ";
        }else if(type.equals("2")){//校内发文
            sql = "select to_char(id) id,to_char(TITLE) name, to_char(pubtime,'yyyy-mm-dd HH24:mi') createdate," +
                    "(SELECT NAME from LBORGANIZATION where id= fbbm) fbr, visits djs, '' xxnr, decode(length(attachment), null, '', " +
                    "'"+oaurl+"/UIProcessor?Table=V_TBLOG_XNTZ&ID='|| id ||'&Column=Attachment&operate=Download&Type=Attachment') attachment, " +
                    "attachment attach, decode(dbms_lob.getlength(picture1), null, '', '"+oaurl+"/FormOperate?Table=V_TBLOG_XNTZ&ID='|| id ||'&Column=Picture1&operate=Download&Type=View') picture1," +
                    " decode(length(picture2), null, '', '"+oaurl+"/FormOperate?Table=V_TBLOG_XNTZ&ID='|| id ||'&Column=Picture2&operate=Download&Type=View') picture2, lyid ";
            sqlwhere = "from TBLOG where category ='502'";
        }

        if(StringUtil.isNotBlank(title)){
            sqlwhere += " and title like '%"+title+"%'";
        }
        if(StringUtil.isNotBlank(stime)){
            sqlwhere += " and to_char(pubtime,'yyyy-mm-dd HH24:mi') >= '"+stime+" 00:00:00'";
        }
        if(StringUtil.isNotBlank(etime)){
            sqlwhere += " and to_char(pubtime,'yyyy-mm-dd HH24:mi') <= '"+etime+" 23:59:59'";
        }
        sqlwhere += " order by pubtime desc";
        sql += sqlwhere;

        notices.addAll(getXxtz(sql, "select count(*) "+sqlwhere, pager));

        if(type.equals("1")){//校内通知
            for(Notice n : notices){
                String id = n.getId();
                String sqla = "select tblog_id id,title name, document doc, '"+oaurl+"/UIProcessor?Table=V_TBLOG_XNTZ&ID='||id ||'&Column=Document&operate=HypotDownload&Type=View&HypotSrcColumn=More' url " +
                        "from lbNewsAttachment where tblog_id = '"+id+"'";
                try {
                    List<Annex> annexes = new DBMUtil("oa").queryAllBeanList(sqla, Annex.class);
                    n.setAnnexs(annexes);
                }catch (Exception e){
                    LOG.error(e);
                }
            }
        }else if(type.equals("2")) {//校内发文

            for(Notice n : notices){
                String attachmentId = n.getLyid();//附件编号
                List<DocumentEntry> documentEntries = LiveBosWebServiceUtils.queryDocumentEntry(attachLiveBosObjName, attachLiveBosFieldName, attachmentId);//查询该发文有哪些附件
                if(documentEntries!=null){
                    List<Annex> annexes = new ArrayList<Annex>(documentEntries.size());
                    for(DocumentEntry documentEntry:documentEntries){
                        Annex annex = new Annex();
                        annex.setName(documentEntry.getFilename());
                        annex.setId( documentEntry.getNo());
                        annex.setDoc(documentEntry.getFilename());
                        annex.setUrl("/s/uc/issue/" + attachmentId + "?downType=attach&itemId=" + documentEntry.getNo());
                        annexes.add(annex);
                    }
                    n.setAnnexs(annexes);
                }
            }
        }

        String noticesStr = JsonUtil.getJSONString(notices);
        return noticesStr;
    }

	/**
	 * 校内发文下载地址
	 * @param issueid 文章id。当要下载文章附件时，该字段传附件表记录的id值
	 * @param request
	 * @return
	 */
	@RequestMapping(value = ActionConstant.App.RequestMapping_issuedown , method = RequestMethod.GET)
	@ResponseBody
	public void getIssueDetail(@PathVariable(value="issueid") String issueid, ModelMap map,
								 HttpServletRequest request, HttpServletResponse response){
        String type = request.getParameter("downType");
        if("attach".equals(type)){//下载附件
            try {
                String itemId = request.getParameter("itemId");
                Document document = LiveBosWebServiceUtils.getDocumentFile(attachLiveBosObjName, attachLiveBosFieldName, issueid, itemId);
                if(document!=null){
                    long length = document.getLength();
                    DataHandler dataHandler = document.getDocumentData();
                    InputStream inputStream = dataHandler.getInputStream();
                    downloadFile(inputStream, length, response);
                }
            } catch (Exception e) {
                LOG.error(e);
                throw new RuntimeException(e.getMessage());
            }
        }else{
            //默认下载发文的正文内容
            String sql = "select attachment filebody from tblog where id = ?";
            List<Notice> list = new DBMUtil("oa").readDoc(issueid, sql);
            Blob blob = list.get(0).getFilebody();
            try {
                downloadFile(blob.getBinaryStream(), blob.length(), response);
            } catch (SQLException e) {
                LOG.error(e);
                throw new RuntimeException(e.getMessage());
            }
        }
	}

    public void downloadFile(InputStream inputStream, long length, HttpServletResponse response){
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=test.doc");
        BufferedOutputStream out = null;
        BufferedInputStream bis = null;
        try{
            bis = new BufferedInputStream(inputStream);
            // 文件写入的缓冲
            byte[] buff = new byte[40960];
            response.setHeader("Content-Length", length + "");
            out = new BufferedOutputStream(response.getOutputStream());
            int len  = 0;
            while((len = bis.read(buff)) != -1){
                out.write(buff,0,len);
                out.flush();
            }
        }catch(Exception e){
            LOG.error(e);
        }finally{
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
            try {
                if(bis != null){
                    bis.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOG.error(e);
                }
            }
        }
    }

    /**
     * 移动端获取代办
     * @param request
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_todos , method = RequestMethod.POST)
    @ResponseBody
    public String getTodos(HttpServletRequest request){
        TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
        String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "1994009";
		}
		*/
		String dbsql = "select * from T_DB t where state = '1'";
		List<TDb> tdbList = DBUtil.queryAllBeanList(dbsql, TDb.class);
		Map<String, String> db_url = new HashMap<String, String>();
		for(TDb tdb : tdbList){
			db_url.put(tdb.getCode(), tdb.getLink());
		}
        DBMUtil db = new DBMUtil();
        String sql = "select t.*,d.link as link from t_lbxx t left join t_db d on t.db = d.code where t.upid = 1 ";
        List<Todo> lbxxs  = new ArrayList<Todo>();
        try {
            List<TLbxx> tlbxxs = db.queryAllBeanList(sql, TLbxx.class);
            sql = "select cur.entry_id as id,case when wf.subject is null  then aa.wf_describe else wf.subject end as title," +
                    "init_t.name as createname,to_char(wf.init_date,'yyyy-MM-dd HH24:mi') as description,";
            for (int j = 0; j < tlbxxs.size(); j++) {
                TLbxx t = tlbxxs.get(j);
                if("1".equals(t.getState())){
					/*
                    String url = t.getUrl();
                    if(StringUtil.isNotBlank(url)&& url.length()>1){
                        url = url.substring(url.indexOf("q=")+2,url.length());
                    }
					*/
					String wfUrl = casLoginUrl + "?service=" + db_url.get(t.getDb()) +"/UIProcessor%3FCreator%3Dworkflow%26Table%3D'||wf.name||'%26WorkID%3D'||wf.id||'%26StepID%3D'||cur.step_id||'%26PageOnly%3Dtrue";

                    StringBuffer sb = new StringBuffer(sql);

                    //sb.append("'" + url + "'");
					sb.append("'" +wfUrl+"'");
                    sb.append(" as url from os_wfentry wf left join os_currentstep cur on wf.id=cur.entry_id left join tuser t on instr(','||cur.owner||',',','||t.id||',')>0 left join ");
                    sb.append(" tuser init_t on wf.initiator=init_t.id left join os_workflowdefs aa on aa.wf_name=wf.name where t.userid= ? order by cur.start_date desc ");
                    DBMUtil dbm = new DBMUtil(t.getDb());
                    List<Todo> tls = dbm.queryAllBeanList(
                            sb.toString(), Todo.class, new Object[]{userid});
                    if(t.getDb().equals("oa")){
                        String oaurl = t.getLink();
                        for(Todo tl : tls){
                            String swsql = "select id from oa_recedocument_njci o where o.instid = ? and sffj ='1' ";
                            List<Map<String, Object>> maps =  dbm.queryForList(null,swsql,tl.getId());//收文
                            if(maps.size()>0){
                                    String id = (BigDecimal)maps.get(0).get("id")+"";
                                    tl.setSfw(oaurl + "/OperateFrame?operate=Download&Table=OA_ReceDocument_NJCI_DJB&Column=Attach&Type=Attachment&PopupWin=false&ID="+id);
									tl.setSfw_type(1);
                            }else{
                                String fwSql = "select id from oa_senddocument_njci o where o.instid = ? and sffj ='1'";
                                List<Map<String, Object>> ms =  dbm.queryForList(null,fwSql,tl.getId());//发文
                                if(ms.size()>0){
                                          String id = (BigDecimal)ms.get(0).get("id")+"";
                                        String projecturl = request.getRequestURL().toString();
                                        tl.setSfw(projecturl.replace("todos","readIssue/")+id);
										tl.setSfw_type(2);
                                }
                            }
                        }
                    }
                    lbxxs.addAll(tls);
                }
            }
        }catch (Exception e){
            LOG.error(e);
        }
        return JsonUtil.getJSONString(lbxxs);
    }


    /**
     * 移动端发文
     * @param request
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_todo_fw , method = RequestMethod.GET)
    @ResponseBody
    public void getFw(@PathVariable String fwid,HttpServletRequest request,HttpServletResponse response){
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=test.doc");

        BufferedOutputStream out = null;
        BufferedInputStream bis = null;
        String sql = "select d.filebody as  from oa_senddocument_njci o left join document_file  d on o.tybsf = d.recordid  where o.id = ?";
        try{
            List<Notice> list = new DBMUtil("oa").readDoc(fwid,sql);
            if(list.size()>0){
                Blob blob = list.get(0).getFilebody();
                bis = new BufferedInputStream(blob.getBinaryStream());
                // 文件写入的缓冲
                byte[] buff = new byte[40960];
                response.setHeader("Content-Length", blob.length() + "");
                out = new BufferedOutputStream(response.getOutputStream());
                int len  =  0;
                while((len = bis.read(buff)) != -1){
                    out.write(buff,0,len);
                    out.flush();
                }
            }
        }catch(Exception e){
            LOG.error(e);
        }finally{
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
            try {
                if(bis != null){
                    bis.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }

        }
    }

    /**
     * 查询所有的移动端服务
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_servers_init , method = RequestMethod.POST)
    @ResponseBody
    public String getServers(HttpServletRequest request){
        TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
        String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "admin";
		}
		*/
        List<TSysMenu> restypes = getServerType();
        String kdysql = "select menuid,menuname,sftj,menupath,upmenuid,tb,djcs,bgcolor,color,belongtoapp,case when ar.id is null then '0' else '1' end as sfydy from t_sys_menu m " +
                "left join (select * from APP_RESOURCE_SUBSCRIBE where userid = ?) ar on m.menuid = ar.resid  where belongtoapp = ? and " +
                " m.ismobile = '1' and (m.appsftj is null or m.appsftj != '1') and exists (select null from t_sys_user a,t_sys_user_role b,t_sys_role c,t_sys_role_menu d " +
                "where a.userid=b.userid and b.roleid=c.roleid and  c.roleid=d.roleid and d.menuid=m.menuid  and c.state=1 and a.userloginid=?) " +
                "and length(menuid)=12 and state=1  order by ar.subscribe_time,upmenuid,ordernum desc,menuid";
        //可订阅的服务（全部服务-已推荐的服务）
        List<TSysMenu> res = DBUtil.queryAllBeanList(kdysql,TSysMenu.class,userid,portalKey,userid);
        AppServerInfo sfi = new AppServerInfo();
        sfi.setRes(res);
        sfi.setRestype(restypes);
        return JsonUtil.getJSONString(sfi);
    }

    /**
     * 查询服务分类
     * @return
     */
    public List<TSysMenu> getServerType(){
        String sql = "select menuid,menuname from t_sys_menu where belongtoapp=?" +
                " and length(menuid)=9 and state=1 order by ordernum desc,menuid";
        //服务分类
        List<TSysMenu> restypes = DBUtil.queryAllBeanList(sql, TSysMenu.class, portalKey);
        return restypes;
    }

    /**
     * 已订阅服务及推荐服务
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_servers_ydy , method = RequestMethod.POST)
    @ResponseBody
    public String getYdyfw(HttpServletRequest request){
        TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
        String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "admin";
		}
		*/
        List<TSysMenu> restypes = getServerType();//服务分类
        String tjfwSql = "select menuid,menuname,sftj,menupath,upmenuid,tb,djcs,bgcolor,color,belongtoapp from t_sys_menu m " +
                " where belongtoapp = ? and " +
                " m.ismobile = '1' and m.appsftj = '1' and exists (select null from t_sys_user a,t_sys_user_role b,t_sys_role c,t_sys_role_menu d " +
                " where a.userid=b.userid and b.roleid=c.roleid and  c.roleid=d.roleid and d.menuid=m.menuid  and c.state=1 and a.userloginid=?) " +
                " and length(menuid)=12 and state=1 order by upmenuid,ordernum desc,menuid ";
        List<TSysMenu> tjfws = DBUtil.queryAllBeanList(tjfwSql,TSysMenu.class,portalKey,userid);
        String ydyfwSql = "select menuid,menuname,sftj,menupath,upmenuid,tb,djcs,bgcolor,color,belongtoapp from t_sys_menu m left join APP_RESOURCE_SUBSCRIBE ar on " +
                " m.menuid = ar.resid " +
                " where belongtoapp = ? and " +
                " m.ismobile = '1' and (m.appsftj is null or m.appsftj !='1') and ar.userid = ? and exists (select null from t_sys_user a,t_sys_user_role b,t_sys_role c,t_sys_role_menu d " +
                " where a.userid=b.userid and b.roleid=c.roleid and  c.roleid=d.roleid and d.menuid=m.menuid  and c.state=1 and a.userloginid=?)  " +
                " and length(menuid)=12 and state=1 order by upmenuid,ordernum desc,menuid ";
        List<TSysMenu> ydyfws = DBUtil.queryAllBeanList(ydyfwSql,TSysMenu.class,portalKey,userid,userid);
        List<TSysMenu> fws = new ArrayList<TSysMenu>();
        fws.addAll(tjfws);
        fws.addAll(ydyfws);
        AppServerInfo sfi = new AppServerInfo();
        sfi.setRes(fws);
        sfi.setRestype(restypes);
        return JsonUtil.getJSONString(sfi);
    }

	/**
	 * 订阅服务
	 * @param menuid
	 * @param request
	 * @return
	 */
    @RequestMapping(value = ActionConstant.App.RequestMapping_servers_dy ,method = RequestMethod.POST)
    @ResponseBody
    public String dyfw(@PathVariable String menuid,HttpServletRequest request){
        TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
        String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "admin";
		}
		*/
        if(StringUtils.isNotBlank(menuid)){
           int a = DBUtil.executeSQL("insert into APP_RESOURCE_SUBSCRIBE(id,userid,resid,SUBSCRIBE_TIME) values(?,?,?,?)",
                    SeqFactory.getNewSequenceAlone(),userid , menuid, DateUtil.formatDate(new Date()));
            return a>0?"true":"false";
        }
        return "false";
    }

    /**
     * 取消订阅
     * @param menuid
     * @param request
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_servers_qxdy ,method = RequestMethod.POST)
    @ResponseBody
    public String qydyfw(@PathVariable String menuid,HttpServletRequest request){
        TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
        String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "admin";
		}
		*/
        if(StringUtils.isNotBlank(menuid)){
            int a = DBUtil.executeSQL("delete from APP_RESOURCE_SUBSCRIBE t where t.resid = ? and t.userid=? ",
                    menuid,userid);
            return a>0?"true":"false";
        }
        return "false";
    }

    /**
     * 功能列表
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_function_list ,method = RequestMethod.POST)
    @ResponseBody
    public String functionList(HttpServletRequest request){
        TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
        String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "admin";
		}
		*/
        String sql ="select t.*,a.datainterface,a.datastyle from APP_FUNCTION_CONFIG t left join app_function_list a on t.functionid = a.id " +
                "where t.isuse = '1' and exists " +
                "(select null from t_sys_user u,t_sys_user_role b,t_sys_role c,app_role_function d " +
                "where u.userid=b.userid and b.roleid=c.roleid and  c.roleid=d.roleid and d.functionid=t.id " +
                "and u.userloginid=?) order by t.orderno";
        List<AppFunctionConfig> list = DBUtil.queryAllBeanList(sql,AppFunctionConfig.class,userid);
        return JsonUtil.getJSONString(list);
    }

    /**
     * 通讯录
     * @return
     */
    @RequestMapping(value = ActionConstant.App.RequestMapping_contact_list ,method = RequestMethod.GET)
    @ResponseBody
    public String contactList(HttpServletRequest request){
        String conSql ="select  id, name, phone, departmentid from app_contacts";
        List<AppContacts> cons = DBUtil.queryAllBeanList(conSql,AppContacts.class);//
        String depSql = "select * from APP_DEPARTMENT t order by orderno";
        List<AppDepartment> deps = DBUtil.queryAllBeanList(depSql,AppDepartment.class);
        AppConDep acd = new AppConDep();
        acd.setContactList(cons);
        acd.setDepartmentList(deps);
        return JsonUtil.getJSONString(acd);
    }

    /**
     * 查询校内通知及发文
     * @param
     * @return
     */
    public List<Notice> getXxtz(String sql, String sqlwhere, Pager pager){
//        sql = "select * from (" + sql + ") where rownum <= 20";
        DBMUtil db = new DBMUtil("oa");
        if(pager != null){
            try {
                long p = db.count(sqlwhere);
                pager.setTotalRows(p); //设置总记录数
            } catch (Exception e) {
                LOG.error(e);
            }

            sql = PageHandler.convert2PagedSQL(pager, sql); // 分页查询
            List<Notice> notices = db.getNotices(sql);
            return notices;
        }else{
            return new ArrayList<Notice>(0);
        }
    }

	/**
	 * 登录跳转(登录过后跳转到jsp页面，在页面中调用appcan js方法跳转到appcan本地页面)
	 * @return
	 */
	@RequestMapping(value = ActionConstant.App.RequestMapping_app_login ,method = RequestMethod.GET)
	public ModelAndView login(HttpServletRequest request){
		Map<String, Object> page = new HashMap<String, Object>();
		TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
		String userloginid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userloginid)){
			userloginid = "1995008";
		}
		*/
		String userid = "";
		String sql = "select userid from USER_ where screenname = ?";
		DBMUtil dbmUtil = new DBMUtil();
		try{
			userid = String.valueOf(dbmUtil.queryFieldValue(sql, userloginid));
		}catch (Exception e){
            LOG.error(e);
		}


		page.put("userloginid", userloginid);
		page.put("userid", userid);
		String uri = "portal/mobile/show";
		ModelAndView mv = new ModelAndView(uri, page);
		return mv;
	}

	/**
	 * 模板页跳转
	 * @param request
	 * @param response
	 * @param name
	 * @param wid
	 * @return
	 */
	@RequestMapping(value = ActionConstant.App.RequestMapping_app_template ,method = RequestMethod.GET)
	public ModelAndView page(HttpServletRequest request,
							 HttpServletResponse response,
							 @PathVariable(value="name") String name,
							 @RequestParam(required = false) String wid){

		TSysUser tSysUser = (TSysUser)request.getSession().getAttribute(IdConstants.SESSION_USER);
		String userid = tSysUser.getUserloginid();
		/*
		if(StringUtils.isBlank(userid)){
			userid = "13704322";
		}
		*/
		Map<String, Object> page = new HashMap<String, Object>();
		String sql = "select * from t_lbxx where wid = '"+wid+"'";
		List<String> head = new ArrayList<String>();
		List<List<String>> content = new ArrayList<List<String>>();
		DBMUtil db = new DBMUtil();
		//sql语句中的参数规则
		Map<String, String> selectSqlParams = new HashMap<String, String>();
		selectSqlParams.put("\\{userid\\}", userid);

		try {
			TLbxx tlbxx = db.queryBean(sql, TLbxx.class);
			DBMUtil dbutil = new DBMUtil(tlbxx.getDb());
			String selectSql = addParamsToSql(selectSqlParams, tlbxx.getSql());
//			System.out.println("sql: " + selectSql);
			List<Map<String, Object>> list = dbutil.queryForList(null, selectSql);
			for(int i = 0; i < list.size(); i++){
				Set<String> keys = list.get(i).keySet();
				List<String> item = new ArrayList<String>();
				for(String key : keys){
					if(i == 0){
						head.add(key);
					}
					item.add((String)list.get(i).get(key));
				}
				content.add(item);
			}
		}catch (Exception e){
            LOG.error(e);
		}

		page.put("pagehead", head);
		page.put("pagecontent", content);

		String uri = "portal/mobile/template/" + name;
		ModelAndView mv = new ModelAndView(uri, page);
		return mv;
	}


	/**
	 * 替换sql语句中的参数
	 * @param params
	 * @param sql
	 * @return
	 */
	private String addParamsToSql(Map<String, String> params, String sql){
		String selectSql = sql;
		Set<String> keySet = params.keySet();
		for(String key : keySet){
			String value = params.get(key);
			selectSql = selectSql.replaceAll(key, value);
		}
		return selectSql;
	}

	/**
	 * app检测更新
	 * @param request
	 * @param response
	 * @param ver 手机上安装的app版本
	 * @param platform 手机平台 1 android 0 ios
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = ActionConstant.App.RequestMapping_check_update ,method = RequestMethod.POST)
	public String checkUpdate(HttpServletRequest request,
							  HttpServletResponse response,
							  @RequestParam(required = false) String ver,
							  @RequestParam(required = false) String platform){

		String sql = "select * from (select * from APP_VERSION where updateflag = 1 and platform = ? order by releasedate desc) where rownum = 1";
		AppVersion appVersion = DBUtil.queryBean(sql, AppVersion.class, platform);
		Map<String, Object> result = new HashMap<String, Object>();
		if(isUpdate(ver, appVersion.getVersion(), platform)){ //需要更新
			result.put("code", "1");
			result.put("detail", appVersion);
		}else{ //不需要更新
			result.put("code", "0");
		}
		return JsonUtil.getJSONString(result);
	}


	/**
	 * 对比app版本号，检测app是否需要升级
	 * @param currentVer  手机目前安装版本
	 * @param recentVer  当前最新版本
	 * @param platform 平台 "1": android,  "0":ios
	 * @return true 需要升级  false 不需要升级
	 */
	private boolean isUpdate(String currentVer, String recentVer, String platform){
		//android
		if("1".equals(platform)){
			String[] oldvers = currentVer.split("\\.");
			String[] newvers = recentVer.split("\\.");
			for(int i = 0; i < oldvers.length; i++){
				int oldVerNum = Integer.parseInt(oldvers[i]);
				int newVerNum = Integer.parseInt(newvers[i]);
				if(newVerNum > oldVerNum){
					return true;
				}else if(newVerNum < oldVerNum){
					return false;
				}
			}
		}
		//ios
		if("0".equals(platform)){
			return false;
		}
		return false;
	}

	/**
	 * 查询周会议
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = ActionConstant.App.RequestMapping_week_conference ,method = RequestMethod.POST)
	public String selectWeekConference(){

		String sql = "select ap.id, ap.week, ap.hyzt content," +
					 "(select wm_concat(hys.hytmc) from T_GWHDGL_HYTGL hys where hys.id in (select column_value from  table(split(ap.sqhycs)))) addr," +
				     "(select wm_concat(b.NAME) from lborganization b where b.ID in  (select * from table(split(ap.sbbm,';')))) department," +
					 "(select listagg(u.name,',')  within group(order by cc.cj,cc.px)  from tuser u left join t_rycc cc on cc.xm=u.id where u.id in (select column_value as hdzjr  from table(split(ap.hdzjr,';')) hdzjrb)) convener," +
				     "to_char(ap.syrq,'hh24:mi') time," +
				     "ap.cjry people, to_char(ap.syrq, 'yyyy-mm-dd') startDate " +
				     "from t_hyap_weekap ap left join t_zc zc on zc.id=ap.yyz left join t_hyap_week hy on hy.id=ap.zhb " +
				     "where hy.zt=3 and to_date(to_char(sysdate,'yyyyMMdd'),'yyyyMMdd') between zc.ksrq and zc.jsrq " +
				     "order by week,ap.syrq,ap.id";

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			List<AppWeekConference> weekConferences = new DBMUtil("oa").queryAllBeanList(sql, AppWeekConference.class);

			result.put("code", "1");
			if(weekConferences != null){
				result.put("detail", weekConferences);
				result.put("size", weekConferences.size());
			}else{
				result.put("size", 0);
			}
		} catch (Exception e) {
			result.clear();
			result.put("code", "0");
            LOG.error(e);
		}

		return JsonUtil.getJSONString(result);
	}

    /**
     * 获取待办tab的id号，便于手机端把待办提醒设置在对应的tab标签上。
     * @return
     */
    @ResponseBody
    @RequestMapping(value = ActionConstant.App.RequestMapping_todoNavTabId ,method = RequestMethod.GET)
    public String getTodoNavTabId(){

        String id = SysPropertiesUtil.get("TodoNavTabId"); //在系统变量参数模块中设置

        return id;
    }

}
